package com.matrix.activemq.topic;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class ProducerTool {
    private String user = ActiveMQConnection.DEFAULT_USER;
    private String password = ActiveMQConnection.DEFAULT_PASSWORD;
    private String url = ActiveMQConnection.DEFAULT_BROKER_URL;
    private String subject = "TopicTest1";
    private Connection connection = null;
    private Destination destination = null;
    private Session session = null;
    private MessageProducer mp = null;

    //初始化
    private void initialize() throws Exception {
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user,password, url);
        connection = connectionFactory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        destination = session.createTopic(subject);
        mp = session.createProducer(destination);
        mp.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
    }

    public void producerMessage(String message) throws Exception {
        initialize();
        TextMessage msg = session.createTextMessage(message);
        connection.start();
        System.out.println("Producer:->Sending Message: " + message);
        mp.send(msg);
        System.out.println("Producer:->Message Sent Completed!");
    }

    public void close() throws Exception {
        System.out.println("Producer:->Closing Connection!");
        if (mp != null) {
            mp.close();
        } else if (session != null) {
            session.close();
        } else if (connection != null) {
            connection.close();
        }

    }

}
